package com.atilim.cargo.algorithm;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.Set;

import com.atilim.cargo.model.Road;
import com.atilim.cargo.model.Vertex;


public class DijkstraAlgorithm {

	public static boolean test = false;
	public static List<Road> roads; //test ederken burası set edilir.
	
	public void computePaths(Vertex source) {
		source.minDistance = 0.;
		PriorityQueue<Vertex> vertexQueue = new PriorityQueue<Vertex>();
		vertexQueue.add(source);

		while (!vertexQueue.isEmpty()) {
			Vertex u = vertexQueue.poll();

			// Bütün bağlantıları(yolun linklerini) dolaş,u ile baglantılı olan yani en üstteki baglantıyla dolaş
			ArrayList<Road> roads = u.getRoads();
			for (Road e : roads) {
				Vertex neigbour = e.getAccros(u);
				double weight = .0;
				if (!test) {
					weight = e.getWeight();	
				} else {
					weight = getRoad(u, neigbour).getWeight();
				}
				
				double distanceThroughU = u.minDistance + weight; //bakılan node'la source arasındaki toplam ağırlık
				if (distanceThroughU < neigbour.minDistance) {
					vertexQueue.remove(neigbour);

					neigbour.minDistance = distanceThroughU;
					neigbour.previous = u;
					vertexQueue.add(neigbour);
				}
			}
		}
	}
	
	public List<Vertex> getShortestPathTo(Vertex target)
    {
        List<Vertex> path = new ArrayList<Vertex>();
        Vertex vertex = target;
        while (vertex != null) {
        	path.add(vertex);
        	vertex = vertex.previous;
        }
//yararlı methodlar var
        Collections.reverse(path);
        return path;
    }
	
	/**
	 * test için
	 * @param allRoads
	 * @param target
	 * @return
	 */
	private Road getRoad (Vertex source, Vertex target){
		for (Road road: roads) {
			if (road.equals(new Road(source, target)))
				return road;
		}
		return null;
	}
}
